// Copyright (c) HashiCorp, Inc.
// SPDX-License-Identifier: MPL-2.0

package securitycenter_test

import (
	"context"
	"fmt"
	"testing"

	"github.com/hashicorp/go-azure-helpers/lang/pointer"
	"github.com/hashicorp/terraform-provider-azurerm/internal/acceptance"
	"github.com/hashicorp/terraform-provider-azurerm/internal/acceptance/check"
	"github.com/hashicorp/terraform-provider-azurerm/internal/clients"
	"github.com/hashicorp/terraform-provider-azurerm/internal/services/securitycenter/parse"
	"github.com/hashicorp/terraform-provider-azurerm/internal/tf/pluginsdk"
)

type ServerVulnerabilityAssessmentVirtualMachineResource struct{}

func testAccServerVulnerabilityAssessmentVirtualMachine_basic(t *testing.T) {
	data := acceptance.BuildTestData(t, "azurerm_security_center_server_vulnerability_assessment_virtual_machine", "test")
	r := ServerVulnerabilityAssessmentVirtualMachineResource{}

	data.ResourceSequentialTest(t, r, []acceptance.TestStep{
		{
			Config: r.basicCfg(data),
			Check: acceptance.ComposeTestCheckFunc(
				check.That(data.ResourceName).ExistsInAzure(r),
			),
		},
		data.ImportStep(),
	})
}

func testAccServerVulnerabilityAssessmentVirtualMachine_requiresImport(t *testing.T) {
	data := acceptance.BuildTestData(t, "azurerm_security_center_server_vulnerability_assessment_virtual_machine", "test")
	r := ServerVulnerabilityAssessmentVirtualMachineResource{}

	data.ResourceSequentialTest(t, r, []acceptance.TestStep{
		{
			Config: r.basicCfg(data),
			Check: acceptance.ComposeTestCheckFunc(
				check.That(data.ResourceName).ExistsInAzure(r),
			),
		},
		data.RequiresImportErrorStep(r.requiresImport),
	})
}

func (ServerVulnerabilityAssessmentVirtualMachineResource) Exists(ctx context.Context, clients *clients.Client, state *pluginsdk.InstanceState) (*bool, error) {
	id, err := parse.VulnerabilityAssessmentVmID(state.ID)
	if err != nil {
		return nil, err
	}

	resp, err := clients.SecurityCenter.ServerVulnerabilityAssessmentClient.Get(ctx, id.ResourceGroup, "Microsoft.Compute", "virtualMachines", id.VirtualMachineName)
	if err != nil {
		return nil, fmt.Errorf("reading %s: %+v", id, err)
	}

	return pointer.To(resp.ID != nil), nil
}

func (ServerVulnerabilityAssessmentVirtualMachineResource) basicCfg(data acceptance.TestData) string {
	return fmt.Sprintf(`
provider "azurerm" {
  features {}
}

resource "azurerm_resource_group" "test" {
  name     = "acctestRG-sva-%[1]d"
  location = "%[2]s"
}

resource "azurerm_virtual_network" "test" {
  name                = "acctestVNet-%[1]d"
  resource_group_name = azurerm_resource_group.test.name
  address_space       = ["192.168.1.0/24"]
  location            = azurerm_resource_group.test.location
}

resource "azurerm_subnet" "test" {
  name                 = "acctestSubnet-%[1]d"
  resource_group_name  = azurerm_resource_group.test.name
  virtual_network_name = azurerm_virtual_network.test.name
  address_prefixes     = ["192.168.1.0/24"]
}

resource "azurerm_network_interface" "test" {
  name                = "acctestNIC-%[1]d"
  location            = azurerm_resource_group.test.location
  resource_group_name = azurerm_resource_group.test.name

  ip_configuration {
    name                          = "vm-%[1]d"
    subnet_id                     = azurerm_subnet.test.id
    private_ip_address_allocation = "Dynamic"
  }
}

resource "azurerm_linux_virtual_machine" "test" {
  name                = "acctestVM-%[1]d"
  location            = azurerm_resource_group.test.location
  resource_group_name = azurerm_resource_group.test.name

  size                            = "Standard_B1s"
  admin_username                  = "testadmin"
  admin_password                  = "Password1234!"
  disable_password_authentication = false

  source_image_reference {
    publisher = "Canonical"
    offer     = "0001-com-ubuntu-server-jammy"
    sku       = "22_04-lts"
    version   = "latest"
  }

  os_disk {
    caching              = "ReadWrite"
    storage_account_type = "Standard_LRS"
  }

  network_interface_ids = [azurerm_network_interface.test.id]
}

resource "azurerm_security_center_subscription_pricing" "test" {
  tier          = "Standard"
  resource_type = "VirtualMachines"
  subplan       = "P2"
}

resource "azurerm_security_center_server_vulnerability_assessment_virtual_machine" "test" {
  virtual_machine_id = azurerm_linux_virtual_machine.test.id
  depends_on         = [azurerm_security_center_subscription_pricing.test]
}
`, data.RandomInteger, data.Locations.Primary)
}

func (r ServerVulnerabilityAssessmentVirtualMachineResource) requiresImport(data acceptance.TestData) string {
	config := r.basicCfg(data)
	return fmt.Sprintf(`
%s
resource "azurerm_security_center_server_vulnerability_assessment_virtual_machine" "import" {
  virtual_machine_id = azurerm_security_center_server_vulnerability_assessment_virtual_machine.test.virtual_machine_id
}
`, config)
}
